import { NextResponse } from 'next/server';
import db from '@/lib/db';
import { Todo } from '@/types/todo';

// 更新待办事项状态
export async function PATCH(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { completed } = await request.json();
    
    if (typeof completed !== 'boolean') {
      return NextResponse.json(
        { error: 'Completed must be a boolean' },
        { status: 400 }
      );
    }

    // 使用默认用户ID 1（临时方案）
    const userId = 1;
    
    // 验证todo属于当前用户
    const existingTodo = db.prepare(
      'SELECT id FROM todos WHERE id = ? AND userId = ?'
    ).get(params.id, userId);

    if (!existingTodo) {
      return NextResponse.json(
        { error: 'Todo not found or access denied' },
        { status: 404 }
      );
    }

    const todo = db.prepare(
      'UPDATE todos SET completed = ? WHERE id = ? AND userId = ? RETURNING *'
    ).get(completed ? 1 : 0, params.id, userId) as Todo | undefined;

    if (!todo) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }

    return NextResponse.json(todo);
  } catch (error) {
    console.error('Error updating todo:', error);
    return NextResponse.json(
      { error: 'Failed to update todo' },
      { status: 500 }
    );
  }
}

// 删除待办事项
export async function DELETE(
  _request: Request,
  { params }: { params: { id: string } }
) {
  try {
    // 使用默认用户ID 1（临时方案）
    const userId = 1;
    
    // 验证todo属于当前用户
    const existingTodo = db.prepare(
      'SELECT id FROM todos WHERE id = ? AND userId = ?'
    ).get(params.id, userId);

    if (!existingTodo) {
      return NextResponse.json(
        { error: 'Todo not found or access denied' },
        { status: 404 }
      );
    }

    const result = db.prepare(
      'DELETE FROM todos WHERE id = ? AND userId = ?'
    ).run(params.id, userId);

    if (result.changes === 0) {
      return NextResponse.json(
        { error: 'Todo not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error deleting todo:', error);
    return NextResponse.json(
      { error: 'Failed to delete todo' },
      { status: 500 }
    );
  }
}